import mqtt
import gpio
import os
import bh1750
import sht30
import led
from Button import Button
import led
global light5
global light4
global light3
global light2
global light1
global leds
global my_but
light5 = led.LED(5)  # 5
light4 = led.LED(9)  # 4
light3 = led.LED(14)  # 3
light2 = led.LED(10)  # 2
light1 = led.LED(13)  # 1
light6 = led.LED(7) # 开关灯光

# 创建按钮
my_but = Button(12)
is_opened = False
leds = [light1,light2,light3,light4,light5]
#暂时没用到
def btnfunc(arg):
    # 1st param is client id
    # 2nd param is the topic string
    # 3rd param is the publish parameter
    # 4th param is the payload which can be a byte list or a string
    # r = mqtt.publish(c, 'hello', mp, [1, 2, 3])
    print('butfunc is called')
    # 发布主题,需要客户,主题,主题信息限制,发布数据
    r = mqtt.publish(c, topic, mp, 'Delphi Tang')
def callback(arg):
    global my_but
    # print('param = ', arg[0])
    # print('id = ', arg[0].id)
    # print('qos = ', arg[0].qos)
    # print('dup = ', arg[0].dup)
    # print('retain = ', arg[0].retain)
    # print('topic = ', arg[1])
    # print('payload = ', str(bytes(arg[2]), 'ascii'))
    decoded = str(bytes(arg[2]), 'ascii')
    print(decoded)
    data = eval(decoded)
    #组件
    item = data['item']
    #状态
    action = data['action']
    if(item =="curtain"):
        cbfunc(None)
        print("yes")
    elif(item =="led" and action =="close"):
        light6.off()
    elif(item =="led" and action =="open"):
        light6.on()
    else:
        print("no")
    # if(decoded=="12"):
    #     # 按钮回调函数(开关灯)
    #     cbfunc(None)
    #     print(decoded)

#开灯方法
def leds_open():
    # i = 0;
    for led in leds:
        led.on()
        os.msleep(100)

    leds.reverse()
    # while i < len(leds):
    #     leds[i].on()
    #     os.msleep(100)
    #     i += 1

#关灯方法
def leds_close():
    # i = 4;
    for led in leds:
        led.off()
        os.msleep(100)
    leds.reverse()
    # while i >= 0:
    #     leds[i].off()
    #     os.msleep(100)
    #     i -= 1

#按钮回调函数
def cbfunc(arg):
    global is_opened
    if is_opened :
        leds_close()
        is_opened = False
    else :
        leds_open()
        is_opened = True


if __name__ == "__main__":
    # 初始化光照传感器
    bh = bh1750.BH1750()
    bh.open()

    # 初始化温湿度传感器
    sht = sht30.SHT30()
    sht.open()

    # 存储传感器数据的字典
    data_dict = {}
    # 服务器ip地址
    host = '192.168.1.199'
    # 服务器端口
    port = 1883
    # 封装连接服务器需要的信息
    n = mqtt.net_connect(host, port)
    print("n=", n)

    # 初始化客户端c
    c = mqtt.client_init(n)
    print("c=", c)

    # 创建客户链接服务端需要的数据结构
    cd = mqtt.ConnData()
    # 版本
    cd.mqtt_version = 3
    # 每次订阅重新连接topic
    cd.clean_session = 1
    # 客户端id
    cd.client_id = 'id'
    # 断联时间
    cd.keep_alive = 60
    # 用户名
    cd.username = 'xuefei'
    # 密码
    cd.password = '12345678'

    # c是客户端用户,cd是用户连接时需要的信息,客户尝试连接服务器
    r = mqtt.connect(c, cd)
    print("r=", r)
    # 创建发布主题的数据结构
    mp = mqtt.MsgParam()
    # 设置链接参数
    mp.qos = 2
    mp.retain = 0
    mp.dup = 0
    mp.id = 0
    # 生成主题,topic1是手机发,箱子收
    topic1 = 'topic1'
    # 生成主题,topic2是箱子发,手机收
    topic2 = 'topic2'
    # 发布主题,需要客户,主题,主题信息限制,发布数据
    r = mqtt.publish(c, topic1, mp, 'xuefeimi')
    r = mqtt.subscribe(c, topic1, 2, callback)
    print('r = ', r)

    print("r")
    while mqtt.is_connected(c):
        sensor_data = {
            'humidity': sht.humidity(),
            'temperature': sht.temperature(),
            'light': bh.read()
        }
        formatted_messages = [
            {"item": "humidity", "value": sensor_data['humidity']},
            {"item": "temperature", "value": sensor_data['temperature']},
            {"item": "light", "value": sensor_data['light']}  # 保留None值
        ]
        for msg in formatted_messages:
            # 处理value值（None转为'null'，字符串需要加引号）
            value = msg['value']
            if value is None:
                value_str = 'null'
            elif isinstance(value, str):
                value_str = '"%s"' % value
            else:
                value_str = str(value)

            # 拼接JSON字符串
            json_str = '{"item": "%s", "value": %s}' % (msg['item'], value_str)
            r = mqtt.publish(c, topic2, mp, json_str)

        # data_dict['light'] = bh.read()  # 光照强度(lux)
        # data_dict['temperature'] = sht.temperature()  # 温度(°C)
        # data_dict['humidity'] = sht.humidity()  # 湿度(%)


        os.handle_event()
        os.msleep(3000)
    # finialize resource
    r = mqtt.unsubscribe(c, topic1)
    # print('r = ', r)
    r = mqtt.disconnect(c)
    # print('r = ', r)
    r = mqtt.client_deinit(c)
    # print('r = ', r)
    r = mqtt.net_disconnect(n)